<template>
  <view class="balance-page">
    <!-- 余额概览卡片 -->
    <view class="balance-card">
      <view class="balance-header">
        <text class="title">账户余额</text>
        <text class="subtitle">(元)</text>
      </view>
      <view class="balance-amount">
        <text class="amount">{{ balance.toFixed(2) }}</text>
      </view>
      <view class="balance-actions">
        <button class="action-btn recharge" @click="navigateToRecharge">充值</button>
        <button class="action-btn withdraw" @click="navigateToWithdraw">提现</button>
      </view>
    </view>

    <!-- 收支明细 -->
    <view class="transaction-list">
      <view class="list-header">
        <text class="title">收支明细</text>
        <text class="filter" @click="showFilter = true">{{ filterText }}</text>
      </view>

      <!-- 筛选弹窗 -->
      <uni-popup ref="filterPopup" type="bottom" :mask-click="true">
        <view class="filter-popup">
          <view class="filter-header">
            <text class="title">选择时间</text>
            <text class="close" @click="showFilter = false">×</text>
          </view>
          <picker-view class="filter-picker" :value="filterValue" @change="handleFilterChange">
            <picker-view-column>
              <view class="filter-item" v-for="(item, index) in filterOptions" :key="index">{{ item.label }}</view>
            </picker-view-column>
          </picker-view>
          <button class="confirm-btn" @click="confirmFilter">确定</button>
        </view>
      </uni-popup>

      <!-- 明细列表 -->
      <view class="list-content" v-if="transactions.length > 0">
        <view 
          class="transaction-item" 
          v-for="(item, index) in transactions" 
          :key="index"
          @click="showDetail(item)"
        >
          <view class="item-left">
            <text class="type">{{ getTypeText(item.type) }}</text>
            <text class="time">{{ formatTime(item.time) }}</text>
          </view>
          <view class="item-right">
            <text class="amount" :class="{ 'income': item.amount > 0, 'expense': item.amount < 0 }">
              {{ item.amount > 0 ? '+' : '' }}{{ item.amount.toFixed(2) }}
            </text>
            <text class="status">{{ getStatusText(item.status) }}</text>
          </view>
        </view>
        
        <!-- 加载更多 -->
        <view class="load-more" v-if="hasMore" @click="loadMore">
          <text>加载更多</text>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view class="empty" v-else>
        <image src="/static/images/empty-wallet.png" class="empty-image" />
        <text class="empty-text">暂无收支记录</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app';

// 账户余额
const balance = ref(3856.50);

// 筛选相关
const filterOptions = ref([
  { label: '全部', value: 'all' },
  { label: '最近7天', value: '7days' },
  { label: '最近30天', value: '30days' },
  { label: '最近3个月', value: '3months' },
  { label: '自定义', value: 'custom' }
]);
const filterValue = ref([0]);
const currentFilter = ref('all');
const showFilter = ref(false);

// 交易记录
const transactions = ref([]);
const page = ref(1);
const pageSize = ref(10);
const hasMore = ref(true);

// 计算属性
const filterText = computed(() => {
  const option = filterOptions.value.find(item => item.value === currentFilter.value);
  return option ? option.label : '全部';
});

// 生命周期
onMounted(() => {
  loadTransactions();
});

// 下拉刷新
onPullDownRefresh(() => {
  page.value = 1;
  hasMore.value = true;
  loadTransactions(true);
});

// 上拉加载更多
onReachBottom(() => {
  if (hasMore.value) {
    page.value += 1;
    loadTransactions();
  }
});

// 加载交易记录
const loadTransactions = (isRefresh = false) => {
  uni.showLoading({ title: '加载中...' });
  
  // 模拟API请求
  setTimeout(() => {
    const mockData = generateMockData(page.value, pageSize.value, currentFilter.value);
    
    if (isRefresh) {
      transactions.value = mockData;
    } else {
      transactions.value = [...transactions.value, ...mockData];
    }
    
    // 模拟没有更多数据的情况
    if (page.value >= 3) {
      hasMore.value = false;
    }
    
    uni.hideLoading();
    if (isRefresh) {
      uni.stopPullDownRefresh();
    }
  }, 800);
};

// 生成模拟数据
const generateMockData = (page, pageSize, filter) => {
  const types = ['recharge', 'withdraw', 'order_payment', 'refund', 'reward'];
  const statuses = ['success', 'processing', 'failed'];
  const now = new Date();
  
  return Array.from({ length: pageSize }, (_, i) => {
    const daysAgo = Math.floor(Math.random() * (page === 1 ? 30 : 90));
    const time = new Date(now);
    time.setDate(now.getDate() - daysAgo - (page - 1) * 30);
    
    const type = types[Math.floor(Math.random() * types.length)];
    let amount = 0;
    
    if (type === 'recharge') {
      amount = 100 + Math.random() * 900;
    } else if (type === 'withdraw') {
      amount = -(50 + Math.random() * 450);
    } else if (type === 'order_payment') {
      amount = -(20 + Math.random() * 480);
    } else if (type === 'refund') {
      amount = 20 + Math.random() * 480;
    } else {
      amount = 1 + Math.random() * 49;
    }
    
    return {
      id: `tx_${page}_${i}`,
      type,
      amount: parseFloat(amount.toFixed(2)),
      status: statuses[Math.floor(Math.random() * statuses.length)],
      time: time.getTime(),
      detail: `这是${getTypeText(type)}的详细说明`
    };
  }).filter(tx => {
    if (filter === 'all') return true;
    const txTime = new Date(tx.time);
    const diffDays = Math.floor((now - txTime) / (1000 * 60 * 60 * 24));
    
    if (filter === '7days') return diffDays <= 7;
    if (filter === '30days') return diffDays <= 30;
    if (filter === '3months') return diffDays <= 90;
    return true;
  });
};

// 获取类型文本
const getTypeText = (type) => {
  const typeMap = {
    recharge: '充值',
    withdraw: '提现',
    order_payment: '订单支付',
    refund: '退款',
    reward: '奖励'
  };
  return typeMap[type] || type;
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    success: '成功',
    processing: '处理中',
    failed: '失败'
  };
  return statusMap[status] || status;
};

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp);
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}`;
};

const padZero = (num) => {
  return num < 10 ? `0${num}` : num;
};

// 筛选变更
const handleFilterChange = (e) => {
  filterValue.value = e.detail.value;
};

// 确认筛选
const confirmFilter = () => {
  currentFilter.value = filterOptions.value[filterValue.value[0]].value;
  showFilter.value = false;
  page.value = 1;
  hasMore.value = true;
  loadTransactions(true);
};

// 查看详情
const showDetail = (item) => {
  uni.navigateTo({
    url: `/pages/wallet/transactionDetail?id=${item.id}`
  });
};

// 导航到充值页面
const navigateToRecharge = () => {
  uni.navigateTo({
    url: '/pages/wallet/recharge'
  });
};

// 导航到提现页面
const navigateToWithdraw = () => {
  uni.navigateTo({
    url: '/pages/wallet/withdraw'
  });
};
</script>

<style lang="scss" scoped>
.balance-page {
  padding: 30rpx;
  min-height: 100vh;
  background-color: $light-bg;
}

.balance-card {
  background-color: $white-bg;
  border-radius: 16rpx;
  padding: 40rpx 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .balance-header {
    display: flex;
    align-items: baseline;
    margin-bottom: 20rpx;
    
    .title {
      font-size: $font-size-32rpx;
      color: $text-color;
      font-weight: bold;
      margin-right: 10rpx;
    }
    
    .subtitle {
      font-size: $font-size-24rpx;
      color: $text-color-666;
    }
  }
  
  .balance-amount {
    margin-bottom: 40rpx;
    
    .amount {
      font-size: 60rpx;
      color: $primary-color;
      font-weight: bold;
    }
  }
  
  .balance-actions {
    display: flex;
    justify-content: space-between;
    
    .action-btn {
      flex: 1;
      height: 80rpx;
      line-height: 80rpx;
      border-radius: 40rpx;
      font-size: $font-size-28rpx;
      color: $white-bg;
      border: none;
      
      &.recharge {
        background-color: $primary-color;
        margin-right: 20rpx;
      }
      
      &.withdraw {
        background-color: $secondary-color;
      }
    }
  }
}

.transaction-list {
  background-color: $white-bg;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    
    .title {
      font-size: $font-size-32rpx;
      color: $text-color;
      font-weight: bold;
    }
    
    .filter {
      font-size: $font-size-26rpx;
      color: $text-color-666;
      
      &::after {
        content: "▼";
        font-size: $font-size-20rpx;
        margin-left: 8rpx;
      }
    }
  }
  
  .transaction-item {
    display: flex;
    justify-content: space-between;
    padding: 30rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .item-left {
      flex: 1;
      
      .type {
        display: block;
        font-size: $font-size-28rpx;
        color: $text-color;
        margin-bottom: 10rpx;
      }
      
      .time {
        font-size: $font-size-24rpx;
        color: $text-color-666;
      }
    }
    
    .item-right {
      text-align: right;
      
      .amount {
        font-size: $font-size-30rpx;
        font-weight: bold;
        margin-bottom: 8rpx;
        
        &.income {
          color: #07C160;
        }
        
        &.expense {
          color: #FF2D2D;
        }
      }
      
      .status {
        display: block;
        font-size: $font-size-22rpx;
        color: $text-color-666;
      }
    }
  }
  
  .load-more {
    text-align: center;
    padding: 30rpx 0;
    color: $primary-color;
    font-size: $font-size-26rpx;
  }
  
  .empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 60rpx 0;
    
    .empty-image {
      width: 200rpx;
      height: 200rpx;
      margin-bottom: 30rpx;
      opacity: 0.6;
    }
    
    .empty-text {
      font-size: $font-size-28rpx;
      color: $text-color-666;
    }
  }
}

.filter-popup {
  background-color: $white-bg;
  border-radius: 24rpx 24rpx 0 0;
  padding: 40rpx 30rpx;
  
  .filter-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 40rpx;
    
    .title {
      font-size: $font-size-32rpx;
      color: $text-color;
      font-weight: bold;
    }
    
    .close {
      font-size: $font-size-40rpx;
      color: $text-color-666;
    }
  }
  
  .filter-picker {
    height: 400rpx;
    
    .filter-item {
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      font-size: $font-size-28rpx;
    }
  }
  
  .confirm-btn {
    margin-top: 40rpx;
    height: 80rpx;
    line-height: 80rpx;
    border-radius: 40rpx;
    background-color: $primary-color;
    color: $white-bg;
    font-size: $font-size-28rpx;
    border: none;
  }
}
</style>